/*
 * Copyright (C) 拾光分享网 
 * All rights reserved, Designed By www.hiai.top.
 * Email：goodsking@163.com.
 * Version：V1.0.2(20230701).
 */
package top.hiai._admin.user;

import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import top.hiai.common.constant.AppConstants;
import top.hiai.common.model.Information;
import top.hiai.common.model.Role;
import top.hiai.common.model.Session;
import top.hiai.common.model.User;
import top.hiai.login.LoginService;

import java.util.Date;
import java.util.List;

/**
 * @Author www.hiai.top
 * @Email goodsking@163.com
 * @Message 更多资源尽在www.hiai.top
 * @Introduction 类的介绍
 */

public class UserAdminService {

    public static final UserAdminService me = new UserAdminService();
    private User userDao = new User().dao();

    /**
     * 获取用户分页
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Page<User> paginate(int pageNum, int pageSize,String q) {
        return userDao.paginate(pageNum, pageSize, "select *", "from bbs_user order by is_auth desc,createAt desc");
    }

    /**
     * 根据ID获取用户信息
     *
     * @param uid
     * @return
     */
    public User findById(int uid) {
        return userDao.findById(uid);
    }

    /**
     * 锁定用户账号
     *
     * @param loginAccountId
     * @param lockedAccountId
     * @return
     */
    public Ret lock(int loginAccountId, int lockedAccountId) {
        if (loginAccountId == lockedAccountId) {
            return Ret.fail().set("msg", "不能锁定自己的账号");
        }

        int n = Db.update("update bbs_user set status = ? where uid=?", User.STATUS_LOCK_ID, lockedAccountId);

        // 锁定后，强制退出登录，避免继续搞破坏
        List<Session> sessionList = Session.dao.find("select * from bbs_session where accountId = ?", lockedAccountId);
        if (sessionList != null) {
            // 处理多客户端同时登录后的多 session 记录
            for (Session session : sessionList) {
                // 清除登录 cache，强制退出
                LoginService.me.logout(session.getSid());
            }
        }

        if (n > 0) {
            return Ret.ok("msg", "锁定成功");
        } else {
            return Ret.fail().set("msg", "锁定失败");
        }
    }

    /**
     * 解锁用户账号
     *
     * @param accountId
     * @return
     */
    public Ret unlock(int accountId) {
        // 如果账户未激活，则不能被解锁
        int n = Db.update("update bbs_user set status = ? where status != ? and uid = ?", User.STATUS_OK, User.STATUS_REG, accountId);
        Db.update("delete from bbs_session where accountId = ?", accountId);
        if (n > 0) {
            return Ret.ok("msg", "解锁成功");
        } else {
            return Ret.fail().set("msg", "解锁失败，可能是账户未激活，请查看账户详情");
        }
    }

    /**
     * 修改用户资料
     * 注意要验证 邮箱是否存在
     *
     * @param
     * @return
     */
    public Ret userUpdate(User user) {
        String email = user.getEmail().toLowerCase().trim();
        String sql = "select uid from bbs_user where lower(email) = ? and uid != ? limit 1";
        Integer id = Db.queryInt(sql, email, user.getUid());
        if (id != null) {
            return Ret.fail().set("msg", "邮箱已经存在，请输入别的邮箱");
        }

        // 暂时只允许修改 nickName 与 userName
        user.keep("uid", "nickName", "email", "sign", "points", "prestige", "views", "is_auth", "authName", "trueName", "authTime");
        user.update();
        return Ret.ok("msg", "账户更新成功");
    }

    /**
     * 标记出 account 拥有的角色
     * 未来用 role left join account_role 来优化
     */
    public void markAssignedRoles(User user, List<Role> roleList) {
        String sql = "select accountId from bbs_account_role where accountId=? and roleId=? limit 1";
        for (Role role : roleList) {
            Integer accountId = Db.queryInt(sql, user.getUid(), role.getId());
            if (accountId != null) {
                // 设置 assigned 用于界面输出 checked
                role.put("assigned", true);
            }
        }
    }

    /**
     * 添加角色
     */
    public Ret addRole(int accountId, int roleId) {
        Record accountRole = new Record().set("accountId", accountId).set("roleId", roleId);
        Db.save("bbs_account_role", accountRole);
        return Ret.ok("msg", "添加角色成功");
    }

    /**
     * 删除角色
     */
    public Ret deleteRole(int accountId, int roleId) {
        Db.delete("delete from bbs_account_role where accountId=? and roleId=?", accountId, roleId);
        return Ret.ok("msg", "删除角色成功");
    }


    public Ret saveSendMsg(Information information) {
        information.setCreateAt(new Date());
        information.setIs_see(0);
        information.save();
        return Ret.ok("msg", "发送成功");
    }

    public boolean setUserPassDefault(Integer uid) {
        User user = new User();
        user.setUid(uid);

        // 密码加盐 hash
        String salt = HashKit.generateSaltForSha256();
        user.setPassword(HashKit.sha256(salt + AppConstants.USER_PASSWORD));
        user.setSalt(salt);

        boolean update = user.update();
        if (update) {
            return true;
        } else {
            return false;
        }
    }

}